package com.at.wc1;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * DataStream实现wordcount：读socket（无界流）
 * TODO 并行度的优先级：
 *      算子 > env > 提交时指定 > 配置文件
 * @author cdhuangchao3
 * @date 2024/4/3 3:51 PM
 */
public class WordCountStreamUnboundedParallelDemo4 {
    public static void main(String[] args) throws Exception {
        // TODO 1.创建执行环境
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 运行时，可以看webUI，一般用于本地测试 需要引入依赖:flink-runtime-web
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        // 设置并行度
        env.setParallelism(3);
        // TODO 2.读取数据：socket
        DataStreamSource<String> socketDS = env.socketTextStream("localhost", 7777);
        // TODO 3.处理数据：切换、转换、分组、聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = socketDS.flatMap((String value, Collector<Tuple2<String, Integer>> out) -> {
                    String[] words = value.split(" ");
                    for (String word : words) {
                        out.collect(Tuple2.of(word, 1));
                    }
                })
                .setParallelism(2) // 只在flatMap算子生效
                .returns(Types.TUPLE(Types.STRING, Types.INT))
                .keyBy(value -> value.f0)
                .sum(1);
        // TODO 4.输出
        sum.print();
        // TODO 5.执行
        env.execute();
    }
}
